<template>
  <div class="apply_container">
    <ZgtCellGroup inset class="mb_20">
      <van-cell
        is-link
        title="购机者类型"
        required
        readonly
        :value="personFlagVal || '请选择'"
        title-class="text_align_left"
        @click="personFlagShow = true"
      />

      <!-- <ZgtPopup v-model="personFlagShow" position="bottom">
        <ZgtPicker show-toolbar :columns="personFlagActions" @confirm="personFlagOnSelect"
          @cancel="personFlagShow = false" />
      </ZgtPopup> -->
    </ZgtCellGroup>

    <ZgtForm @failed="onFailed" @submit="onSubmit">
      <ZgtCellGroup inset>
        <!-- 个人录入 -->
        <van-cell
          v-if="personFlag === 0"
          title="姓名"
          required
          title-class="text_align_left"
        >
          <template value>
            <ZgtField
              v-model="formData.name"
              placeholder="请输入姓名"
              readonly
              input-align="right"
              error-message-align="right"
              :rules="formRules.name"
            />
          </template>
        </van-cell>

        <van-cell
          v-if="personFlag === 0"
          title="性别"
          required
          title-class="text_align_left"
        >
          <template value>
            <ZgtField
              is-link
              v-model="formData.sex"
              placeholder="请选择"
              input-align="right"
              readonly
              error-message-align="right"
              :rules="formRules.sex"
              @click="sexShow = true"
            />

            <ZgtPopup v-model="sexShow" position="bottom">
              <ZgtPicker
                show-toolbar
                :columns="sexOptions"
                @confirm="sexSelect"
                @cancel="sexShow = false"
              />
            </ZgtPopup>
          </template>
        </van-cell>

        <van-cell
          v-if="personFlag === 0"
          title="身份证号码"
          required
          title-class="text_align_left"
        >
          <template value>
            <ZgtField
              v-model="formData.idCard"
              placeholder="请输入身份证号码"
              readonly
              input-align="right"
              error-message-align="right"
              :rules="formRules.idCard"
            />
          </template>
        </van-cell>

        <van-cell
          v-if="personFlag === 0"
          title="身份证住址"
          required
          title-class="text_align_left"
        >
          <template value>
            <ZgtField
              v-model="formData.address"
              placeholder="请输入身份证住址"
              input-align="right"
              error-message-align="right"
              :rules="formRules.address"
            />
          </template>
        </van-cell>

        <van-cell
          v-if="personFlag === 0"
          title="现住址"
          required
          title-class="text_align_left"
        >
          <template value>
            <ZgtField
              v-model="formData.nowAddress"
              placeholder="请输入现住址"
              input-align="right"
              error-message-align="right"
              :rules="formRules.nowAddress"
            />
          </template>
        </van-cell>

        <!-- 组织录入 -->
        <van-cell
          v-if="personFlag === 1"
          title="组织名称"
          required
          title-class="text_align_left"
        >
          <template value>
            <ZgtField
              v-model="formData.name"
              placeholder="请输入组织名称"
              readonly
              input-align="right"
              error-message-align="right"
              :rules="formRules.name"
            />
          </template>
        </van-cell>

        <van-cell
          v-if="personFlag === 1"
          title="统一社会信用代码"
          required
          title-class="text_align_left"
        >
          <template value>
            <ZgtField
              v-model="formData.idCard"
              placeholder="请输入统一社会信用代码"
              readonly
              input-align="right"
              error-message-align="right"
              :rules="formRules.idCard"
            />
          </template>
        </van-cell>

        <van-cell
          v-if="personFlag === 1"
          title="营业执照注册住所"
          required
          title-class="text_align_left"
        >
          <template value>
            <ZgtField
              v-model="formData.addressOrg"
              placeholder="请输入营业执照注册住所"
              input-align="right"
              error-message-align="right"
              :rules="formRules.addressOrg"
            />
          </template>
        </van-cell>

        <van-cell
          v-if="personFlag === 1"
          title="法定代表人姓名"
          required
          title-class="text_align_left"
        >
          <template value>
            <ZgtField
              v-model="formData.legalPersonName"
              placeholder="请输入法定代表人姓名"
              readonly
              input-align="right"
              error-message-align="right"
              :rules="formRules.legalPersonName"
            />
          </template>
        </van-cell>

        <van-cell
          v-if="personFlag === 1"
          title="法定代表人身份证号"
          required
          title-class="text_align_left"
        >
          <template value>
            <ZgtField
              v-model="formData.legalIdCard"
              placeholder="请输入身份证号"
              readonly
              input-align="right"
              error-message-align="right"
              :rules="formRules.legalIdCard"
            />
          </template>
        </van-cell>

        <van-cell
          v-if="personFlag === 1"
          title="法定代表人身份证住址"
          required
          title-class="text_align_left"
        >
          <template value>
            <ZgtField
              v-model="formData.address"
              placeholder="请输入身份证住址"
              input-align="right"
              error-message-align="right"
              :rules="formRules.address"
            />
          </template>
        </van-cell>

        <van-cell
          v-if="personFlag === 1"
          title="法定代表人现住址"
          required
          title-class="text_align_left"
        >
          <template value>
            <ZgtField
              v-model="formData.nowAddress"
              placeholder="请输入现住址"
              input-align="right"
              error-message-align="right"
              :rules="formRules.nowAddress"
            />
          </template>
        </van-cell>

        <van-cell title="申请所属乡镇" required title-class="text_align_left">
          <template value>
            <ZgtField
              is-link
              v-model="formData.town"
              placeholder="请选择"
              input-align="right"
              readonly
              error-message-align="right"
              :rules="formRules.town"
              @click="townsShow = true"
            />

            <ZgtPopup v-model="townsShow" position="bottom">
              <van-cascader
                v-model="formData.areaCode"
                title="请选择所在乡镇"
                :options="cascadeData"
                @close="townsShow = false"
                :field-names="fieldNames"
                @finish="selectTowns"
              />
            </ZgtPopup>
          </template>
        </van-cell>

        <van-cell title="申请所属村" title-class="text_align_left">
          <template value>
            <ZgtField
              is-link
              v-model="formData.village"
              placeholder="请选择"
              input-align="right"
              readonly
              error-message-align="right"
              :rules="formRules.village"
              @click="villageShow = true"
            />
            <ZgtPopup v-model="villageShow" position="bottom">
              <ZgtPicker
                show-toolbar
                value-key="label"
                :columns="villageActions"
                @confirm="selectVillage"
                @cancel="villageShow = false"
              />
            </ZgtPopup>
          </template>
        </van-cell>

        <van-cell title="申请所属组" title-class="text_align_left">
          <template value>
            <ZgtField
              v-model="formData.group"
              placeholder="请输入申请所属组"
              input-align="right"
              error-message-align="right"
              :rules="formRules.group"
            />
          </template>
        </van-cell>
      </ZgtCellGroup>

      <div class="submit_btn">
        <ZgtButton
          round
          color="#096AE6"
          block
          type="primary"
          native-type="submit"
        >
          提交
        </ZgtButton>
      </div>
    </ZgtForm>
  </div>
</template>

<script lang="js">
import { saveBuyerInfo } from '@/api/index'
import {
  ZgtCellGroup,
  ZgtPicker,
  ZgtPopup,
  ZgtForm,
  ZgtField,
  ZgtButton
} from '@/components/zgt-comps'

import { EncryptSM4 } from '@/utils/allSM'
import { generateGuid } from '@/utils'
import { mapState } from 'vuex'
export default {
  components: {
    ZgtCellGroup,
    ZgtPicker,
    ZgtPopup,
    ZgtForm,
    ZgtField,
    ZgtButton
  },
  data() {
    return {
      // 申请类型选择
      personFlagShow: false,
      personFlagActions: [
        { text: '个人', value: 0 },
        { text: '组织', value: 1 }
      ],
      personFlag: '', // 个人0 组织1
      personFlagVal: '',

      // 表单内容
      formData: {
        name: undefined, // 机主姓名/组织名称
        idCard: undefined, // 身份证号码/统一社会信用代码
        sex: undefined, // 性别(男，女)
        address: undefined, // 身份证住址/法定代表人身份证住址
        nowAddress: undefined,
        addressOrg: undefined, // 组织营业执照注册住所
        legalPersonName: undefined, // 法定代表人姓名
        legalIdCard: undefined, // 法定代表人身份证号
        areaCode: undefined, // 申请所属乡镇完整区域码(示例：180901010000)
        town: undefined, // 乡镇
        village: undefined, // 村
        group: undefined, // 组
      },
      formRules: {},

      // 性别
      sexOptions: [
        { text: '男', value: '男' },
        { text: '女', value: '女' }
      ],
      sexShow: false,

      townsShow: false,
      fieldNames: {
        text: 'label',
        value: 'value',
        children: 'children',
      },
      // 村选择
      villageShow: false,
      villageActions: []
    }
  },
  computed: {
    ...mapState({
      sidebar: (state) => state
    }),
    // 市镇级联数据
    cascadeData: function () {
      return this.$store.state.area
    }
  },
  created() {
    this.init()
  },
  methods: {
    init() {
      let type = this.sidebar.userType
      if (type == 1) {
        if (!this.sidebar.personalInfo) return
        this.personFlag = this.personFlagActions[0].value
        this.personFlagVal = this.personFlagActions[0].text

        let userInfo = this.sidebar.personalInfo
        this.formData.name = userInfo.userName
        this.formData.idCard = userInfo.userIdcard
        userInfo.userSex && (this.formData.sex = userInfo.userSex == 'F' ? '女' : '男')
      } else {
        if (!this.sidebar.corporationInfo) return
        this.personFlag = this.personFlagActions[1].value
        this.personFlagVal = this.personFlagActions[1].text

        let userInfo = this.sidebar.corporationInfo
        this.formData.name = userInfo.enterpriseName || ''
        this.formData.idCard = userInfo.idcardNum || ''
        this.formData.legalPersonName = userInfo.legalName || ''
        this.formData.legalIdCard = userInfo.legalIdcardNum || ''
        this.formData.address = userInfo.legalAddress || ''
      }

      this.initRules()
    },
    initRules() {
      this.formRules = {
        name: [{ required: true, message: `请输入${this.personFlag == 0 ? '用户名' : '组织名称'}` }],
        idCard: [{ required: true, message: `请输入${this.personFlag == 0 ? '身份证号码' : '统一社会信用代码'}` }],
        sex: [{ required: true, message: '请选择' }],
        address: [{ required: true, message: `请输入${this.personFlag == 0 ? '身份证住址' : '法定代表人身份证住址'}` }],
        nowAddress: [{ required: true, message: `请输入${this.personFlag == 0 ? '现住址' : '法定代表人现住址'}` }],
        addressOrg: [{ required: true, message: '请输入营业执照注册住所' }],
        legalPersonName: [{ required: true, message: '请输入法定代表人姓名' }],
        legalIdCard: [{ required: true, message: '请输入法定代表人身份证号' }],
        town: [{ required: true, message: '请选择' }],
        // village: [{ required: true, message: '请选择' }],
        // group: [{ required: true, message: '请输入申请所属组' }],
      }
    },
    // 选择申请类型
    personFlagOnSelect(data) {
      this.personFlag = data.value
      this.personFlagVal = data.text
      this.personFlagShow = false
      this.initRules()
    },
    // 选择性别
    sexSelect(data) {
      this.formData.sex = data.value
      this.sexShow = false
    },
    // 选择乡镇
    selectTowns(data) {
      if (data) {
        this.formData.town = data.selectedOptions[data.tabIndex].label
        this.formData.areaCode = data.value
        this.formData.village = ''
        this.villageActions = data.selectedOptions[data.tabIndex].village
      }
      this.townsShow = false
    },
    // 选择村
    selectVillage(data) {
      if (data) {
        this.formData.village = data.label
      }
      this.villageShow = false
    },
    // 校验失败
    onFailed(errorInfo) {
      console.log('errorInfo', errorInfo);
    },
    // 提交信息
    onSubmit() {
      let params = {
        ...this.formData,
        personFlag: this.personFlag,
        operatorId: this.$store.state.uid,
        id: generateGuid()
      }
      if (params.village == '无') {
        params.village = ''
      }
      if (!(params.areaCode.slice(6, 8) > 0 && params.areaCode.slice(8) == 0)) {
        this.$zgtToast.fail({
          message: '请选择到乡镇'
        })
        return 
      }
      console.log('提交参数', params);
      this.$zgtToast.loading({
        message: '加载中...',
        forbidClick: true,
      });
      saveBuyerInfo({ jsons: EncryptSM4(JSON.stringify(params)) })
        .then(res => {
          this.$zgtToast(res.msg)
          setTimeout(() => {
            this.$router.go(-1)
          }, 2000)
        })
        .catch((err) => {
          console.log('err', err);
          // this.$zgtToast.clear();
        })
    },
  }
}
</script>

<style lang="less" scoped>
.apply_container {
  padding: 20px 0;
  background-color: #f4f7fc;
  flex: 1;

  .text_align_left {
    text-align: left;
  }

  .mb_20 {
    margin-bottom: 20px;
  }

  .zgt-field {
    padding: 0;

    &::after {
      display: none;
    }
  }

  .submit_btn {
    margin: 32px 16px 16px;

    .zgt-button {
      .zgt-button__content {
        .zgt-button__text {
          font-size: 16px;
        }
      }
    }
  }
}
</style>

<style lang="less">
.zgt-field__error-message {
  display: none;
}
</style>
